<style scoped>
.xcom-wapper{
  position: relative;
  width:100%;
  height:36px;
}

.xcom-com{
  position: absolute;
  top:0px;
  left:0px;
}

.switch-btn{
  width:30px;
  height:16px;
  line-height:16px;
  text-align:center;
  color:#373941;
  background-color: #FFF;
  margin-left:auto;
  border-radius: 3px;
  cursor: pointer;
  font-size:12px;
  position: absolute;
  top:50%;
  margin-top:-8px;
  left:150px;
}

.disable{
  opacity: 0.3;
}

</style>
<template>
<div class="xcom-wapper">
  <slider v-if="dataType===1" class="xcom-com" :value="data" @input="inputHandle1" :min="min" :max="max" :label="label" :unit="unit"/>
  <slider v-if="dataType===2" class="xcom-com" :value="data2" @input="inputHandle2" :min="0" :max="100" :label="label" unit="%"/>
  <div class="switch-btn" :class="{'disable':!enable}" @click.stop.prevent="switchHandle">切换</div>
</div>

</template>
<script>
import slider from '@/components/slider'
export default {
  props: {
    min: {
      type: Number,
      default: 0
    },
    max: {
      type: Number,
      default: 100
    },
    label: {
      type: String,
      default: '设置项'
    },
    value: {
      type: [Number, String]
    },
    unit: {
      type: String,
      default: 'px'
    }
  },
  components: {
    slider
  },
  data () {
    return {
      data: null,
      dataCache: this.min,
      data2: null,
      data2Cache: 0,
      dataType: 1
    }
  },
  computed: {
    enable () {
      return !(typeof this.value === 'undefined' || this.value === null)
    }
  },
  methods: {
    inputHandle1 (val) {
      this.$emit('input', val)
    },
    inputHandle2 (val) {
      this.$emit('input', val + '%')
    },
    switchHandle () {
      if (this.dataType === 1) {
        this.dataCache = this.data
        this.dataType = 2
        this.$emit('input', this.data2 + '%')
        return
      }

      if (this.dataType === 2) {
        this.data2Cache = this.data2
        this.dataType = 1
        this.$emit('input', this.data)
      }
    }
  },
  watch: {
    value () {
      if ((typeof this.value !== 'undefined') && (this.value !== null)) {
        if (this.value.toString().slice(-1) === '%') {
          this.dataType = 2
          this.data2 = parseInt(this.value.slice(0, -1))
          this.data = this.dataCache
        } else {
          this.dataType = 1
          this.data = parseInt(this.value)
          this.data2 = this.data2Cache
        }
      } else {
        this.dataType = 1
        this.data = this.data2 = null
      }
    }
  }

}
</script>
